package com.jt.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.jt.pojo.Cart;
import com.jt.pojo.Order;
import com.jt.pojo.User;
import com.jt.service.DubboCartService;
import com.jt.service.DubboOrderService;
import com.jt.util.UserThreadLocal;
import com.jt.vo.SysResult;
import org.aspectj.weaver.ast.Or;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("/order")
public class OrderController {

    @Reference(check = false)
    private DubboCartService cartService;
    @Reference(check = false)
    private DubboOrderService orderService;


    /**
     * 跳转订单确认页面
     * 1.url:http://www.jt.com/order/create.html
     * 2.参数:没有参数 null
     * 3.返回值:order-cart
     * 4.页面取值: ${carts}
     * 业务逻辑: 根据userId,之后查询购物车记录信息.之后在页面中展现购物车数据.
     */
    @RequestMapping("/create")
    public String create(HttpServletRequest request, Model model){

//        User user = (User) request.getAttribute("JT_USER");
//        long userId = user.getId();
        Long userId = UserThreadLocal.get().getId();
        List<Cart> cartList = cartService.findCartListByUserId(userId);
        model.addAttribute("carts",cartList);
        return "order-cart";
    }

    /**
     * 实现订单的入库
     * 1.url:http://www.jt.com/order/submit
     * 2.参数: 整个form表单利用order对象接收
     * 3.返回值:SysResult对象  并且包含orderId数据
     * 业务:订单入库时应该入库三张表记录  order  orderShipping orderItems
     *      orderId由登录用户id+当前时间戳手动拼接
     *      并且要求三个对象的主键值相同
     */
    @RequestMapping("/submit")
    @ResponseBody
    public SysResult submit(Order order,HttpServletRequest request){
        Long userId = UserThreadLocal.get().getId();
        order.setUserId(userId);        //将userId进行赋值操作.
        String orderId = orderService.saveOrder(order);
        if(StringUtils.isEmpty(orderId)){
            //说明:后端服务器异常
            return SysResult.fail();
        }
        return SysResult.success(orderId);
    }


    /**
     * 实现订单的查询 根据orderId
     * url地址:http://www.jt.com/order/success.html?id=191598258114066
     * 参数：id=191598258114066
     * 返回值:success页面
     * 页面参数:${order.orderId}
     */
    @RequestMapping("/success")
    public String findOrderById(String id,Model model){
        Order order = orderService.findOrderById(id);
        model.addAttribute("order",order);
        return "success";
    }

}
